package com.itheima.admin.xxl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.itheima.admin.service.XxlJobService;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsDtoSave;
import com.itheima.wemedia.fagin.AdWmNewsFeign;
import com.itheima.wemedia.vo.WmNewsVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class MySample {

    //注入service对象
    @Autowired
    private XxlJobService xxlJobService;

    //注入远程调用自媒体微服务对象
    @Autowired
    private AdWmNewsFeign adWmNewsFeign;

    //创建定时调度方法
    @XxlJob("syncArticleJob")
    public ReturnT<String> syncArticleJob(String param) {
        //远程调用自媒体微服务获取，WmNewsVo对象
        ResultVo<List<WmNewsVo>> listResultVo = adWmNewsFeign.wmNewsList(new WmNewsDtoSave());
        //获取查询到的数据
        List<WmNewsVo> wmNewsVoList = listResultVo.getData();
        //判断远程调用数据是否查询成功
        log.info("开始调用定时发布任务{}", param);
        if (!listResultVo.isSuccess()) {
            log.info("远程掉用自媒体微服务查询文章失败");
            XxlJobLogger.log("远程掉用自媒体微服务查询文章失败");
            return ReturnT.FAIL;
        }
        log.info("更新同步了{}篇文章", wmNewsVoList.size());
        //判断是查询到的数据是否为空
        if (CollectionUtils.isEmpty(wmNewsVoList)) {
            log.info("代发布(审核通过)文章为空,不需要执行下面代码");
        } else {
            //遍历查询到的集合封装
            for (WmNewsVo wmNewsVo : wmNewsVoList) {
                //调用service进行处理
                ResultVo resultVo = xxlJobService.syncArticleJob(wmNewsVo);
                if (!resultVo.isSuccess()) {
                    log.info("远程调用同步到文章库失败！");
                    XxlJobLogger.log("远程调用同步到文章库失败");
                    return ReturnT.FAIL;
                }
            }
        }
        return ReturnT.SUCCESS;
    }
}
